package LC;

/**
 * https://leetcode.com/problems/first-missing-positive/description/
 * Given an unsorted integer array,
 * find the first missing positive integer.
 * For example,
 * Given [1,2,0] return 3,
 * and [3,4,-1,1] return 2.
 * Your algorithm should run in O(n) time and uses constant space.
 */
public class LC_041_FirstMissingPositive_Array_Exchange {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 10};
        System.out.println(Solution.firstMissingPositive(a));
        System.out.println(Solution_2.firstMissingPositive(a));
    }

    static class Solution {
        static int firstMissingPositive(int[] nums) {
            int len = nums.length;
            for (int i = 0; i < len; ) {
                if (nums[i] != i + 1 && nums[i] > 0 && nums[i] <= len && nums[i] != nums[nums[i] - 1]) {
                    swap(i, nums[i] - 1, nums);
                } else {
                    i++;
                }
            }
            for (int i = 1; i <= len; i++) {
                if (nums[i - 1] != i) {
                    return i;
                }
            }
            return len + 1;
        }

        private static void swap(int i, int j, int[] nums) {
            nums[i] = nums[i] ^ nums[j];
            nums[j] = nums[i] ^ nums[j];
            nums[i] = nums[i] ^ nums[j];
        }
    }

    static class Solution_2 {
        static int firstMissingPositive(int[] nums) {
            for (int i = 0; i < nums.length; i++) {
                while (nums[i] != i + 1) {
                    if (nums[i] <= 0 || nums[i] >= nums.length || nums[i] == nums[nums[i] - 1])
                        break;
                    int temp = nums[i];
                    nums[i] = nums[nums[i] - 1];
                    nums[temp - 1] = temp;
                }
            }
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] != i + 1)
                    return i + 1;
            }
            return nums.length + 1;
        }
    }

}
